package com.efounder.activity;

import android.graphics.Color;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.adapter.OrderAdapter;
import com.efounder.adapter.OrderPagerAdapter;
import com.efounder.bean.OrderList;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.utils.MallRequestUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ORDER_LIST_URL;

/**
 * Created by will on 18-3-1.
 */

public class MallGeneralOrderActivity extends BaseActivity {

    private String TAG = this.getClass().getSimpleName();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private String[] titles;
    private List<BadgeView> mBadgeViews = new ArrayList<>();
    private View view;
    private int targetIndex = 0;
    private int toShipCount = 0, toCheckCount = 0, toReceiveCount = 0, toCommentCount = 0, refundCount = 0;
    private OrderPagerAdapter orderPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_my_order);
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mail_my_order);
        if (getIntent().getExtras()!=null&&getIntent().getExtras().get("targetIndex") != null) {
            targetIndex = (int)getIntent().getExtras().get("targetIndex");
        }
        titles = getResources().getStringArray(R.array.order_types);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        EventBus.getDefault().register(this);
        initViewPager();
        initTabLayout();
        initBadge();
        initData();
    }



    private void initViewPager() {
        orderPagerAdapter = new OrderPagerAdapter(getSupportFragmentManager(), titles);
        viewPager.setAdapter(orderPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //在这里刷新数据,保证数据同步,评论页不刷新
//                Fragment item = orderPagerAdapter.getItem(position);
//                if(item instanceof MallOrderFragment){
//                    orderPagerAdapter.notifyDataSetChanged();
//                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initTabLayout() {
        for (int i=0;i<titles.length;i++) {
            tabLayout.addTab(tabLayout.newTab().setText(titles[i]));
        }
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(targetIndex).select();

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getCustomView() != null) {
                    ((TextView)tab.getCustomView()).setTextColor(getResources().getColor(R.color.black));
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab.getCustomView() != null) {
                    ((TextView)tab.getCustomView()).setTextColor(getResources().getColor(R.color.gray));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("status", "all");
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("num", "0");
        map.put("pageSize", "5");
        MallRequestUtil.getRequest(TAG, ORDER_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    OrderList orderList = gson.fromJson(response, OrderList.class);
                    if (orderList.getResult().equals("success") && orderList.getStatusCounts() != null) {
                        resetCount();
                        for (OrderList.StatusCountsBean statusCountsBean : orderList.getStatusCounts()) {
                            if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_PAY)) {
                                toCheckCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_SEND_GOOD)) {
                                toShipCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_RECEIVE)) {
                                toReceiveCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_COMMENT)) {
                                toCommentCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_REFUND)) {
                                refundCount = statusCountsBean.getCount();
                            }
                        }
                    }
                    refreshBadge();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
            }
        });
    }

    /**
     * 重置角标
     */
    private void resetCount() {
        toShipCount = 0; toCheckCount = 0; toReceiveCount = 0; toCommentCount = 0; refundCount = 0;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveCartBadgeEvent(UpdateOrderBadgeEvent event) {
        initData();
    }

    private void initBadge() {
        for (int i = 1; i <= 4; i++){
            TextView textView = (TextView)((LinearLayout)((LinearLayout)tabLayout.getChildAt(0)).getChildAt(i)).getChildAt(1);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
            layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
            layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
            BadgeView badgeView = new BadgeView(this, textView);
            badgeView.setBadgeMargin(0, 10);
            badgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
            badgeView.setTextSize(11);
            int badgeCount = 0;
            if (i == 1) {
                badgeCount = toCheckCount;
            }else if (i == 2){
                badgeCount = toShipCount;
            }else if (i == 3){
                badgeCount = toReceiveCount;
            }
            else if (i == 4){
                badgeCount = toCommentCount;
            }
        if (badgeCount > 99) {
            badgeView.setText("99+");
        } else {
            badgeView.setText(badgeCount + "");
        }
            //ShortcutBadger.applyCount(context, badgeCount);
            badgeView.setBadgeBackgroundColor(getResources().getColor(
                    R.color.red));
        if (badgeCount <= 0 && badgeCount != -1) {
            badgeView.setVisibility(View.INVISIBLE);
        } else {
            badgeView.show();
        }
            mBadgeViews.add(badgeView);
        }

    }

    private void refreshBadge() {
        for (int i = 1; i <= 4; i++){
            BadgeView badgeView = (BadgeView)((FrameLayout)((LinearLayout)((LinearLayout)tabLayout.getChildAt(0)).getChildAt(i)).getChildAt(1)).getChildAt(1);

            int badgeCount = 0;
            if (i == 1) {
                badgeCount = toCheckCount;
            }else if (i == 2){
                badgeCount = toShipCount;
            }else if (i == 3){
                badgeCount = toReceiveCount;
            }
            else if (i == 4){
                badgeCount = toCommentCount;
            }
            if (badgeCount > 99) {
                badgeView.setText("99+");
            } else {
                badgeView.setText(badgeCount + "");
            }
            //ShortcutBadger.applyCount(context, badgeCount);
            badgeView.setBadgeBackgroundColor(Color.RED);
            if (badgeCount <= 0 && badgeCount != -1) {
                badgeView.setVisibility(View.INVISIBLE);
            } else {
                badgeView.show();
            }
            mBadgeViews.add(badgeView);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(orderPagerAdapter!=null){
            orderPagerAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
